from hashlib import md5
from pathlib import Path

from win32com.client import Dispatch

word_app = Dispatch('Word.Application')
word_app.Visible = False


class OpenWordFile(object):
    def __init__(self, path):
        path = str(path.resolve().absolute()) if isinstance(path, Path) else path
        self.doc = word_app.Documents.Open(path)

    def __enter__(self):
        return self.doc

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.doc and self.doc.Close()


def create_file(tgt):
    """创建文件"""
    path_ins = tgt if isinstance(tgt, Path) else Path(tgt)
    if not path_ins.parent.exists():
        path_ins.parent.mkdir(parents=True, exist_ok=True)
    if not path_ins.exists():
        path_ins.touch()
    return path_ins.absolute()


def get_md5(_):
    b = b''
    if isinstance(_, Path):
        b = _.read_bytes()
    elif isinstance(_, str):
        b = _.encode('utf-8')
    elif hasattr(_, 'read'):
        if callable(_.read):
            b = _.read()
    else:
        b = str(_).encode('utf-8')

    m = md5()
    m.update(b)
    return m.hexdigest()
